package com.ztgf.order.scheduled;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.dto.pay.PayOrderLogDTO;
import com.ztgf.order.models.dto.purchase.PurchaseInfoDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.service.common.ICommonService;
import com.ztgf.order.models.service.pay.IPayOrderLogService;
import com.ztgf.order.models.service.purchase.IPurchaseInfoService;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.pay.models.service.IPayOrderService;
import com.ztgf.shopping.models.bo.shop.CorpAuthInfoBO;
import com.ztgf.shopping.models.dto.shop.ShopQiyuesuoInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopQiyuesuoInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2018/01/26 14:10
 */
@Component
@Slf4j
public class ScheduledTimes {
    @DubboReference
    private IOrderPaymentScaleService orderPaymentScaleService;
    @DubboReference
    private IOrderPaymentTypeService orderPaymentTypeService;
    @DubboReference
    private IShopQiyuesuoInfoService shopQiyuesuoInfoService;
    @DubboReference
    private IOrderStatusService orderStatusService;
    @DubboReference
    private IOrderContractRelationService orderContractRelationService;
    @DubboReference
    private IOrderInfoService orderInfoService;
    @DubboReference
    private IOrderExpirationDateService orderExpirationDateService;
    @DubboReference
    private IOrderPayRelationService orderPayRelationService;
    @DubboReference
    private IOrderReturnExpirationDateService orderReturnExpirationDateService;
    @DubboReference
    private IOrderReturnCommodityService orderReturnCommodityService;

    @DubboReference
    private IPurchaseInfoService purchaseInfoService;

    @DubboReference
    private IPayOrderLogService payOrderLogService;

    @DubboReference
    private IPayOrderService payOrderService;

    @DubboReference
    private ICommonService commonService;

    /**
     * 暂时 每1分钟执行一次 更新订单过期时间
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void executeOrderExcepire() {
//        log.info("--------------定时任务：订单过期检测开启 ------------------");
        boolean isSelect = true;
        Long lastNo = 0L;
        do {
            List<OrderExpirationDateDTO> allExpireOrderInfo = orderExpirationDateService.getAllExpireOrderInfo(lastNo);
            if (allExpireOrderInfo.size() < 50) {
                isSelect = false;
            }
            for (OrderExpirationDateDTO orderExpirationDateDTO : allExpireOrderInfo) {
                lastNo = orderExpirationDateDTO.getOrderId();
                OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderExpirationDateDTO.getOrderId());
                if (null == orderStatusDTO) {
                    continue;
                }
                if (orderStatusDTO.getIsExpiration() == 1) {//已经过期不用
                    continue;
                }
                try{
                    Integer orderState = orderStatusDTO.getOrderState();
                    orderStatusDTO.setIsExpiration(1);//设置订单已经过期
                    Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
                    wrapper.eq("order_id", orderStatusDTO.getOrderId());
                    wrapper.eq("order_state", orderState);
                    orderStatusService.update(orderStatusDTO, wrapper);
                } catch (ServiceException e){
                    log.error("订单过期检测开启: " + orderExpirationDateDTO.getId(), e);
                }

            }
        } while (isSelect);
//        log.info("--------------定时任务：订单过期检测结束 ------------------");
    }

    /**
     * 每 半个小时执行一次 获取最新的企业的认证状态
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0,30 * * * ?")
    public void executeReportCQSSC() {
//        log.info("--------------定时任务：获取企业验证信息开始 ------------------");
        //获取企业申请中企业信息
        List<ShopQiyuesuoInfoDTO> shopQiyuesuoInfoDTOList = shopQiyuesuoInfoService.getListAuthenticationing();
        for (ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO : shopQiyuesuoInfoDTOList) {
            CorpAuthInfoBO corpAuthInfoBO = null;
            try {
                corpAuthInfoBO = shopQiyuesuoInfoService.getEnterpriseAuthenticationState(shopQiyuesuoInfoDTO.getCompanyName());
                if (null == corpAuthInfoBO) {
                    log.error("契约锁企业验证请求异常");
                }
            } catch (Exception e) {
                log.error("契约锁企业验证请求异常");
                return;
            }
            if (null != corpAuthInfoBO.getStatus() && "2".equals(corpAuthInfoBO.getStatus().toString())) {
                shopQiyuesuoInfoDTO.setAuthenticationStatus("2");
                shopQiyuesuoInfoService.updateById(shopQiyuesuoInfoDTO);
            }
        }
//        log.info("--------------定时任务：获取企业验证信息结束 ------------------");
    }

//    /**
//     * 每 半个小时执行一次 获取最新的 废弃合同状态
//     *
//     * @throws Exception
//     */
//    @Scheduled(cron = "0 0,30 * * * ?")
//    public void executeReportCQSSCAbandonContactState() {
//        log.info("--------------定时任务：废弃合同状态检测开启 ------------------");
//        boolean isSelect = true;
//        Long lastNo = 0L;
//        do {
//            List<OrderStatusDTO> orderStatusDTOList = orderStatusService.getListSignAbandonOrder(lastNo);
//            if (orderStatusDTOList.size() < 50) {
//                isSelect = false;
//            }
//
//            for (OrderStatusDTO orderStatusDTO : orderStatusDTOList) {
//                lastNo = orderStatusDTO.getOrderId();
//                OrderContractRelationDTO orderContractRelationDTO = orderContractRelationService.getByOrderId(orderStatusDTO.getOrderId());
//                String contractId = orderContractRelationDTO.getContractId();
//                if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode()) {//买家签订中
//                    boolean b = shopQiyuesuoInfoService.getSignContactState(Long.parseLong(contractId), 1);//买家
//                    if (b) {//签署完成
//                        try {
//                            orderInfoService.signOver(orderStatusDTO.getOrderId(), OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode());
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    continue;
//                }
//                if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode()) {//卖家签订中
//                    boolean b = shopQiyuesuoInfoService.getSignContactState(Long.parseLong(contractId), 2);//卖家
//                    if (b) {//签署完成
//                        try {
//                            orderInfoService.signOver(orderStatusDTO.getOrderId(), OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode());
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        } while (isSelect);
//
//        log.info("--------------定时任务：废弃合同态检测结束 ------------------");
//    }

    /**
     * 每 半个小时执行一次 获取最新的 合同状态
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void executeReportCQSSCContactState() {
//        log.info("--------------定时任务：合同状态检测开启 ------------------");
        boolean isSelect = true;
        Long lastNo = 0L;
        do {
            List<OrderStatusDTO> orderStatusDTOList = orderStatusService.getListAuthingOrder(lastNo);
            if (orderStatusDTOList.size() < 50) {
                isSelect = false;
            }

            for (OrderStatusDTO orderStatusDTO : orderStatusDTOList) {
                lastNo = orderStatusDTO.getOrderId();
                OrderContractRelationDTO orderContractRelationDTO = orderContractRelationService.getByOrderId(orderStatusDTO.getOrderId());
                if(orderContractRelationDTO == null){
                    continue;
                }
                String contractId = orderContractRelationDTO.getContractId();
//                log.info("0--------------合同检测开始------------------orderId="+orderStatusDTO.getOrderId()+"-------contractId="+contractId);
                if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode()) {//买家签订中
//                    log.info("1--------------买家合同检测中------------------orderStatus="+OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode());
                    boolean b = shopQiyuesuoInfoService.getSignContactState(Long.parseLong(contractId), 1);//买家
//                    log.info("2--------------买家合同检测中------------------contractStatus="+b);
                    if (b) {//签署完成
                        try {
//                            log.info("3--------------买家合同检测start------------------"+orderStatusDTO.getOrderId()+"---------type="+OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode());
                            orderInfoService.signOver(orderStatusDTO.getOrderId(), OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode());
//                            log.info("4--------------买家合同检测end------------------");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    continue;
                }
                if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode()) {//卖家签订中
//                    log.info("5--------------卖家合同检测中------------------orderStatus="+OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode());
                    boolean b = shopQiyuesuoInfoService.getSignContactState(Long.parseLong(contractId), 2);//卖家
//                    log.info("6--------------卖家合同检测中------------------contractStatus="+b);
                    if (b) {//签署完成
                        try {
//                            log.info("7--------------卖家合同检测start------------------"+orderStatusDTO.getOrderId()+"type="+OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode());
                            orderInfoService.signOver(orderStatusDTO.getOrderId(), OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode());
//                            log.info("8--------------卖家合同检测end------------------");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } while (isSelect);

//        log.info("--------------定时任务：合同状态检测结束 ------------------");
    }

    /**
     * @Description: 检查售后订单过期
     * @Author: WangChenYu
     * @Param: []
     * @Date: 2020-10-12 16:58
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void executeAfterOrderExpiration() {
//        log.info("--------------定时任务：售后订单过期检测开启 ------------------");
        boolean isSelect = true;
        Long lastNo = 0L;
        do {
            List<OrderReturnExpirationDateDTO> expirationDateList = orderReturnExpirationDateService.queryAllExpirationAfterOrder(lastNo);
            if (null != expirationDateList && expirationDateList.size() > 0) {
                if (expirationDateList.size() < 50) {
                    isSelect = false;
                }
                for (OrderReturnExpirationDateDTO orderReturnExpirationDateDTO : expirationDateList) {
                    lastNo = orderReturnExpirationDateDTO.getOrderReturnId();
                    OrderReturnCommodityDTO orderReturnCommodityDTO = orderReturnCommodityService.selectById(orderReturnExpirationDateDTO.getOrderReturnId());
                    if (null == orderReturnCommodityDTO) {
                        continue;
                    }
                    if (orderReturnCommodityDTO.getAfterSalesState() == 3) {
                        continue;
                    }

                    try{
                        if (orderReturnCommodityDTO.getType() == 0) {
                            //退货处理
                            if (orderReturnCommodityDTO.getShipState() == 4 && orderReturnExpirationDateDTO.getStatus() == 4) {
                                commonService.saveReturnReceive(orderReturnCommodityDTO);
                            }
                        } else {
                            //换货处理
                            if (orderReturnCommodityDTO.getShipState() == 3 && orderReturnExpirationDateDTO.getStatus() == 3) {
                                orderReturnCommodityService.updateBuyersSignFo(orderReturnCommodityDTO.getId());
                            }
                        }
                    } catch (ServiceException e){
                        log.error("售后订单过期检测开启: " + orderReturnExpirationDateDTO.getId(), e);
                    } catch (RuntimeException e){
                        log.error("售后订单过期检测开启RuntimeException: " + orderReturnExpirationDateDTO.getId(), e);
                    }


                }
            } else {
                isSelect = false;
            }
        } while (isSelect);
//        log.info("--------------定时任务：售后订单过期检测结束 ------------------");
    }

    /**
     * @Description: 每分钟执行检查订单到期自动签收
     * @Author: chenyu.wang
     * @Params: []
     * @Date: 2020.12.08 14:03
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void executeOrderExpiration() {
//        log.info("--------------定时任务：订单签收检测开始 ------------------");
        boolean isSelect = true;
        Long lastNo = 0L;
        Date date = new Date();
        do {
            Page<OrderStatusDTO> page = new Page<>(0, 50);
            // 查询待签收的订单
            Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("order_state", 4);
            wrapper.gt("order_id", lastNo);
            wrapper.orderBy("order_id", true);
            Page<OrderStatusDTO> selectPage = orderStatusService.selectPage(page, wrapper);
            List<OrderStatusDTO> selectList = selectPage.getRecords();
            if (selectList != null && selectList.size() > 0) {
                if (selectList.size() < 50) {
                    isSelect = false;
                }
                for (OrderStatusDTO orderStatus : selectList) {
                    lastNo = orderStatus.getOrderId();
                    // 查询订单待签收倒计时
                    Wrapper<OrderExpirationDateDTO> dtoWrapper = new EntityWrapper<>();
                    dtoWrapper.eq("order_id", lastNo)
                            .eq("status", 4)
                            .eq("is_flag", 0);
                    OrderExpirationDateDTO selectOne = orderExpirationDateService.selectOne(dtoWrapper);
                    if (selectOne != null && date.after(selectOne.getExpirationTime())) {
                        log.info("订单自动签收,订单号:{}", selectOne.getOrderId());
                        try{
                            commonService.saveReceive(selectOne.getOrderId(), false);
                        } catch (ServiceException e){
                            log.error("订单自动签收: " + selectOne.getOrderId(), e);
                        }

                    }
                }
            } else {
                isSelect = false;
            }
        } while (isSelect);
//        log.info("--------------定时任务：订单签收检测结束 ------------------");
    }


    /**
     * @Description: 每分钟执行检查采购订单是否过期
     * @Author: chenyu.wang
     * @Params: []
     * @Date: 2020.12.08 14:03
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void executePurchaseInfo() {
//        log.info("--------------定时任务：采购订单是否过期 ------------------");
        boolean isSelect = true;
        Date date = new Date();
        do {
            Page<PurchaseInfoDTO> page = new Page<>(0, 50);
            // 查询待签收的订单
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq("bargain_status", 0);
            wrapper.eq("del_flag", 0);
            wrapper.lt("expired_time", DateUtils.getCurrentDateTime());
            wrapper.orderBy("id", true);
            Page<PurchaseInfoDTO> selectPage = purchaseInfoService.selectPage(page, wrapper);
            List<PurchaseInfoDTO> dtoList = selectPage.getRecords();
            if (dtoList != null && dtoList.size() > 0) {
                if (dtoList.size() < 50) {
                    isSelect = false;
                }
                for (PurchaseInfoDTO dto : dtoList) {
                    if(dto.getExpiredTime() != null && dto.getExpiredTime().getTime() <= date.getTime()){
                        try{
                            purchaseInfoService.saveFinishPurchaseInfo(dto, 1, null, null, null, null, null);
                        } catch (ServiceException e){
                            log.error("采购订单是否过期: " + dto.getId(), e);
                        }

                    }
                }
            } else {
                isSelect = false;
            }
        } while (isSelect);
//        log.info("--------------定时任务：采购订单是否过期 ------------------");
    }


    /**
     * @Description: 支付回调
     * @Author: chenyu.wang
     * @Params: []
     * @Date: 2020.12.08 14:03
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void executePayNotify() {
//        log.info("--------------定时任务：支付回调 ------------------");
        boolean isSelect = true;
        do {
            Page<PayOrderLogDTO> page = new Page<>(0, 50);
            // 查询待签收的订单
            Wrapper wrapper = new EntityWrapper<>();
            Object[] status = {0, 1};
            wrapper.in("status", status);
            Object[] payType = {0, 1};
            wrapper.in("pay_type", payType);
            wrapper.orderBy("id", true);
            Page<PayOrderLogDTO> selectPage = payOrderLogService.selectPage(page, wrapper);
            List<PayOrderLogDTO> dtoList = selectPage.getRecords();
            if (dtoList != null && dtoList.size() > 0) {
                if (dtoList.size() < 50) {
                    isSelect = false;
                }
                for (PayOrderLogDTO dto : dtoList) {
                    try{
                        wrapper = new EntityWrapper<>();
                        wrapper.eq("business_order_water_no", dto.getId().toString());
                        PayOrderDTO payOrderDTO = payOrderService.selectOne(wrapper);
                        log.error("--------business_order_water_no------------"+ JSON.toJSONString(payOrderDTO));
                        if(payOrderDTO != null){
                            payOrderLogService.savePaySuccessNotify(payOrderDTO);
                        } else {
                            if(dto.getCreateTime().getTime() <= DateUtils.addSecond(new Date(), -20).getTime()){
                                PayOrderLogDTO newDTO = new PayOrderLogDTO();
                                newDTO.setStatus(3);
                                wrapper = new EntityWrapper<>();
                                wrapper.eq("id", dto.getId());
                                wrapper.eq("status", 0);
                                payOrderLogService.update(newDTO, wrapper);
                            }
                        }
                    } catch (ServiceException e){
                        log.error("支付回调: " + dto.getId(), e);
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    } catch (RuntimeException e){
                        log.error("支付回调RuntimeException: " + dto.getId(), e);
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    } catch (Exception e){
                        log.error("支付回调Exception: " + dto.getId(), e);
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                    log.error("--------PayOrderLogDTO dto  执行完成------------"+ JSON.toJSONString(dto));
                }
            } else {
                isSelect = false;
            }
        } while (isSelect);
//        log.info("--------------定时任务：支付回调 ------------------");
    }



    /**
     * @Description: 每分钟执行检查订单逾期次数
     * @Author: Eric
     * @Params: []
     * @Date: 2022.01.06 14:03
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void orderTradNum() {
//        log.info("--------------定时任务：每分钟执行检查哪些订单逾期并修改 ------------------");
        boolean isSelect = true;
        Long lastNo = 0L;
        do {
            //查询出赊销订单
            Page<OrderPaymentTypeDTO> page = new Page<>(0, 50);
            Wrapper<OrderPaymentTypeDTO> wrapper = new EntityWrapper();
            wrapper.eq("payment_type", 2);
            wrapper.eq("type", 1);
            wrapper.gt("id",lastNo);
            wrapper.orderBy("id", true);
            Page<OrderPaymentTypeDTO> selectPage = orderPaymentTypeService.selectPage(page, wrapper);
            List<OrderPaymentTypeDTO> dtoList = selectPage.getRecords();
//            log.info("===========================dtoList"+dtoList.size());
            if (dtoList != null && dtoList.size() > 0) {
                if (dtoList.size() < 50) {
                    isSelect = false;
                }
                // 查询出赊销订单的关联支付
                for (OrderPaymentTypeDTO orderPaymentTypeDTO : dtoList) {
                    lastNo=orderPaymentTypeDTO.getId();
                    EntityWrapper<OrderStatusDTO> orderStatusDTOEntityWrapper = new EntityWrapper<>();
                    orderStatusDTOEntityWrapper.eq("order_id",orderPaymentTypeDTO.getOrderId());
                    OrderStatusDTO orderStatusDTO = orderStatusService.selectOne(orderStatusDTOEntityWrapper);
                    if (orderStatusDTO.getOrderState()==0 || orderStatusDTO.getOrderState()==6 || orderStatusDTO.getOrderState()==7){
                       if (orderStatusDTO.getOrderState()==6 || orderStatusDTO.getOrderState()==7){
                           EntityWrapper<OrderPaymentScaleDTO> scaleDTOEntityWrapper = new EntityWrapper<>();
                           scaleDTOEntityWrapper.eq("order_id",orderStatusDTO.getOrderId());
                           List<OrderPaymentScaleDTO> list = orderPaymentScaleService.selectList(scaleDTOEntityWrapper);
                           for (OrderPaymentScaleDTO orderPaymentScaleDTO : list) {
                               orderPaymentScaleDTO.setOverdueTimes(0);
                               orderPaymentScaleService.updateById(orderPaymentScaleDTO);
                           }
                       }
                        continue;
                    }
                    //售后变成无需支付
                    EntityWrapper<OrderPaymentScaleDTO> wrapper2 = new EntityWrapper<>();
                    wrapper2.eq("order_id",orderPaymentTypeDTO.getOrderId());
                    wrapper2.eq("payment_status",4);
                    List<OrderPaymentScaleDTO> orderPaymentScaleDTOS1 = orderPaymentScaleService.selectList(wrapper2);
                    if (orderPaymentScaleDTOS1!=null && orderPaymentScaleDTOS1.size()>0){
                        for (OrderPaymentScaleDTO orderPaymentScaleDTO : orderPaymentScaleDTOS1) {
                            orderPaymentScaleDTO.setOverdueTimes(0);
                            orderPaymentScaleService.updateById(orderPaymentScaleDTO);
                        }
                    }

                    EntityWrapper<OrderPaymentScaleDTO> wrapper1 = new EntityWrapper<>();
                    wrapper1.eq("order_id",orderPaymentTypeDTO.getOrderId());
                    wrapper1.in("payment_status","0,1,3");
                    List<OrderPaymentScaleDTO> orderPaymentScaleDTOS = orderPaymentScaleService.selectList(wrapper1);
                    //判断是否已经有逾期次数了
                    if(orderPaymentScaleDTOS!=null && orderPaymentScaleDTOS.size()>0){
                        for (OrderPaymentScaleDTO orderPaymentScaleDTO : orderPaymentScaleDTOS) {
                            if (orderPaymentScaleDTO.getOverdueTimes()==1){
                                continue;
                            }
                            if (orderPaymentScaleDTO.getPaymentTime()!=null){
                                //判断是否逾期
                                long num =comparTime(DateUtils.getCurrentDateTime(), orderPaymentScaleDTO.getPaymentTime());
                                log.info("num===================="+num);
                                if (num<0){
                                    orderPaymentScaleDTO.setOverdueTimes(1);
                                    orderPaymentScaleService.updateById(orderPaymentScaleDTO);
                                }
                            }

                        }
                    }

                }


            } else {
                isSelect = false;
            }
        } while (isSelect);
//        log.info("--------------定时结束：每分钟执行检查哪些订单逾期并修改 ------------------");
    }

    public static int comparTime(Date date,Date date1){
        long time = date.getTime();
        long time1 = date1.getTime();
        long a=  time1-time;
        if (a>0){
            return 1;
        }
        if (a<0){
            return -1;
        }
        if (a==0){
            return 0;
        }
        return 0;
    }

}
